package ma.mindware.mpm.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import ma.mindware.met.core.account.Action;
import ma.mindware.met.core.account.User;
import ma.mindware.met.core.technicalservice.DBService;
import ma.mindware.met.core.technicalservice.ServiceRunner;
import ma.mindware.met.core.technicalservice.TechnicalServiceException;

public class Init implements HttpSessionListener, ServletContextListener {

	public static String configFile="WEB-INF/conf/config.properties";
	HashMap<Long,HttpSession> connectedUser=new HashMap<Long,HttpSession>();

	@SuppressWarnings("unchecked")
	public void contextInitialized(ServletContextEvent sce) {
		
	Properties config=new Properties();
	try {
		config.load(sce.getServletContext().getResourceAsStream(configFile));		
		sce.getServletContext().setAttribute("config", config);
		ServiceRunner serviceRunner=ServiceRunner.getInstance();
		Object[] serviceParams=new Object[1];
		serviceParams[0]=config.getProperty("dbInfoFilePath");
		try {
			ArrayList<Action> actions = (ArrayList<Action>) serviceRunner.run(DBService.class, serviceParams, "list", new Action());
			sce.getServletContext().setAttribute("actions", actions);
		}catch (TechnicalServiceException e) {
			e.printStackTrace();
		}
		
		System.out.println("Notice:MRMC Started :)");
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	}

	
	/**
	 * this method is called when application is stoped
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("Notice:MRMC Stopped :(");
	}
	
	public void sessionCreated(HttpSessionEvent se) {
              
    }
 
    @SuppressWarnings("unchecked")
	public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        User user= (User) session.getAttribute("user");
        if(user!=null){
        	ServletContext context     = session.getServletContext();
        	connectedUser=(HashMap<Long,HttpSession>) context.getAttribute("users");
        	connectedUser.remove(user.getAccountID());
        }
    }

}
